package com.example.utilsandviews;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.widget.RelativeLayout;
import android.widget.SeekBar;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.cwj.mylibrary.AppVersionNameAndCode;
import com.cwj.mylibrary.ChinaDate;
import com.cwj.mylibrary.ChinaDate2;
import com.cwj.mylibrary.LunarUtils;
import com.cwj.mylibrary.MarketUtils;
import com.cwj.mylibrary.NetworkUtils;
import com.cwj.mylibrary.OneClickThree;
import com.cwj.mylibrary.RegularVerification;
import com.cwj.mylibrary.TimeUtils;
import com.cwj.mylibrary.ToastUtil;
import com.cwj.mylibrary.WaterMarkUtil;
import com.example.utilsandviews.broadcast.BatteryReceiver;
import com.example.utilsandviews.databinding.ActivityMainBinding;
import com.example.utilsandviews.views.FallObject;

import java.util.Calendar;

import jp.wasabeef.glide.transformations.BlurTransformation;

public class MainActivity extends BaseActivity {

    private ActivityMainBinding binding;
    private BatteryReceiver receiver;
    private final String urlStr = "https://www.baidu.com/";
    private int mohuchengdu = 25;
    private int caiyanglv = 5;

    @Override
    protected RelativeLayout getLayoutId() {
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void initView() {

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void initData() {
        //初始化一个雪花样式的fallObject
        @SuppressLint("UseCompatLoadingForDrawables") FallObject.Builder builder = new FallObject.Builder(getResources().getDrawable(R.drawable.icon_huaban));
        FallObject fallObject = builder
                .setSpeed(3, true)
                .setSize(55, 55, true)
                .setWind(5, true, true)
                .build();
        binding.fallingView.addFallObject(fallObject, 30);//添加下落物体对象

        //年月日时分秒显示
        binding.tvTime.setText(TimeUtils.dateToString(TimeUtils.getTimeStame(), "yyyy年MM月dd日 HH:mm:ss"));
        //网络连接情况
        setWangluo();

        //版本号展示
        binding.tvCode.setText(AppVersionNameAndCode.getVersionName(this) +
                "(" + AppVersionNameAndCode.getVersionCode(this) + ")");

        //农历转公历，农历月，若为闰月则传入负数
        try {
            //公历转yyyy-MM-dd格式的农历
            String nYMD = ChinaDate2.solarToLunar(TimeUtils.dateToString(TimeUtils.getTimeStame(), "yyyy-MM-dd"), true);
            String[] nY = nYMD.split("-");

            //将农历日期转换为公历日期
            if (nY[1].contains("闰")) {
                int year = Integer.parseInt(nY[0]);
                int month = Integer.parseInt(nY[1].substring(1));
                int monthDay = Integer.parseInt(nY[2]);
                binding.tvNToG.setText(LunarUtils.getTranslateSolarString(year, -month, monthDay));
            } else {
                int year = Integer.parseInt(nY[0]);
                int month = Integer.parseInt(nY[1]);
                int monthDay = Integer.parseInt(nY[2]);
                binding.tvNToG.setText(LunarUtils.getTranslateSolarString(year, month, monthDay));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //公历转农历
        binding.tvNToG.setText(LunarUtils.getTranslateLunarString(Integer.parseInt(TimeUtils.dateToString(TimeUtils.getTimeStame(), "yyyy")), Integer.parseInt(TimeUtils.dateToString(TimeUtils.getTimeStame(), "MM")), Integer.parseInt(TimeUtils.dateToString(TimeUtils.getTimeStame(), "dd"))));
        //公历转农历(带天干地支和属相)
        ChinaDate lunar = new ChinaDate(Calendar.getInstance());
        binding.tvGToN2.setText("" + lunar);

        //判断无限网络是否开启
        binding.scWuxianWangluo.setChecked(NetworkUtils.getWifiEnabled(this));

        //是否启用无限网络
        binding.scWuxianWangluo.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                NetworkUtils.setWifiEnabled(this, true);

                Handler handler = new Handler();
                handler.postDelayed(this::setWangluo, 3000);
            } else {
                NetworkUtils.setWifiEnabled(this, false);

                Handler handler = new Handler();
                handler.postDelayed(this::setWangluo, 3000);
            }
        });

        //验证手机号
        binding.btnYanzheng.setOnClickListener(v -> {
            if (!RegularVerification.isMobileNO(binding.etPhone.getText().toString())) {
                ToastUtil.s(this, "手机号格式不正确");
            } else {
                loadingDialog.setMessage("验证中...");
                loadingDialog.show();

                new Handler(msg -> {
                    loadingDialog.dismiss();
                    ToastUtil.imageLS(MainActivity.this, "验证成功", R.drawable.icon_huaban);
                    return false;
                }).sendEmptyMessageDelayed(0, 2000);
            }
        });

        //是否全屏显示（隐藏状态栏和字体）true表示全屏
        binding.sc.setOnCheckedChangeListener((buttonView, isChecked) -> fullScreen(isChecked));

        //为当前Activity添加水印
        WaterMarkUtil.showWatermarkView(MainActivity.this, "Hello World!");

        //自定义太极
        binding.btnStart.setOnClickListener(v -> {
            binding.tj.createAnimation();//动画开始  继续
        });

        binding.btnStop.setOnClickListener(v -> {
            binding.tj.stopAnimation();//动画暂停
        });

        //注册电池电量广播监听
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        receiver = new BatteryReceiver(binding.bv, binding.bv2, binding.tvDianliang);
        registerReceiver(receiver, filter);

        IntentFilter filter2 = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        receiver = new BatteryReceiver(binding.bv, binding.bv2, binding.tvDianliang2);
        registerReceiver(receiver, filter2);

        //跳转到应用市场
        binding.tvBaidu.setOnClickListener(v -> {
            //携带链接打开UC浏览器
            MarketUtils.getTools().openInstalledAppInURL(MainActivity.this, "com.UCMobile", "com.UCMobile.main.UCMobile", urlStr);
        });

        binding.tvMohuchengdu.setText("模糊程度（" + mohuchengdu + ")：");
        binding.tvCaiyanglv.setText("采样率（" + caiyanglv + ")：");
        //高斯模糊效果
        //BlurTransformation 第一个参数是1-25范围，随着数字越大，模糊度越高，第二个参数代表采样率，数字越大，越模糊
        Glide.with(this).load(R.drawable.icon_bg)
                .apply(RequestOptions.bitmapTransform(new BlurTransformation(mohuchengdu, caiyanglv)))
                .into(binding.ivGaosimohu);
        binding.sbMohuchengdu.setProgress(mohuchengdu);
        binding.sbCaiyanglv.setProgress(caiyanglv);
        //改变模糊程度
        binding.sbMohuchengdu.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mohuchengdu = progress;
                binding.tvMohuchengdu.setText("模糊程度（" + mohuchengdu + ")：");
                //高斯模糊效果
                //BlurTransformation 第一个参数是1-25范围，随着数字越大，模糊度越高，第二个参数代表采样率，数字越大，越模糊
                Glide.with(MainActivity.this).load(R.drawable.icon_bg)
                        .apply(RequestOptions.bitmapTransform(new BlurTransformation(mohuchengdu, caiyanglv)))
                        .into(binding.ivGaosimohu);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //改变采样率
        binding.sbCaiyanglv.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                caiyanglv = progress;
                binding.tvCaiyanglv.setText("采样率（" + caiyanglv + ")：");
                //高斯模糊效果
                //BlurTransformation 第一个参数是1-25范围，随着数字越大，模糊度越高，第二个参数代表采样率，数字越大，越模糊
                Glide.with(MainActivity.this).load(R.drawable.icon_bg)
                        .apply(RequestOptions.bitmapTransform(new BlurTransformation(mohuchengdu, caiyanglv)))
                        .into(binding.ivGaosimohu);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //防连续点击
        binding.btnOneclick.setOnClickListener(v -> {
            if (!OneClickThree.isFastClick()) {
                ToastUtil.s(this, "点击了我");
            } else {
                ToastUtil.s(this, "请不要连续操作");
            }
        });
    }

    @SuppressLint("SetTextI18n")
    private void setWangluo() {
        binding.tvWangluo.setText((NetworkUtils.isConnected(this) ? "有网络连接" : "无网络连接") + "\n" +
                (NetworkUtils.getWifiEnabled(this) ? "Wifi已开启" : "Wifi未开启") + "\n" +
                (NetworkUtils.isWifiConnected(this) ? "Wifi已连接" : "Wifi未连接") + "\n" +
                (NetworkUtils.isWifiAvailable(this) ? "Wifi可用" : "Wifi不可用") + "\n" +
                (NetworkUtils.isMobileData(this) ? "正在使用移动数据" : "未使用移动数据") + "\n" +
                (NetworkUtils.is4G(this) ? "正在使用4G数据" : "未使用4G数据") + "\n" +
                ("网络返回类型：" + NetworkUtils.getNetworkType(this)) + "\n" +
                ("ipv4：" + NetworkUtils.getIPAddress(true)) + "\n" +
                ("通过wifi返回ip地址：" + NetworkUtils.getIpAddressByWifi(this))
        );
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁广播
        unregisterReceiver(receiver);
    }
}